package com.qf.tenant.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.tea.TeaException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.dto.SMSDto;
import com.qf.tenant.entity.Tenant;
import com.qf.tenant.mapper.TenantMapper;
import com.qf.tenant.service.TenantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.utils.SMSUtil;
import com.qf.vo.R;
import com.qf.vo.Result;
import com.qf.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-10-26
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result<Tenant> addTenant(Tenant tenant) {
        //1、通过输入用户名查询数据库中该对象是否存在，如果存在提示该对象已经存在（该对象在数据库中存在的）
        String tenantName=tenant.getName();
        QueryWrapper<Tenant>queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Tenant::getName,tenantName);
        Tenant tenantDb=tenantMapper.selectOne(queryWrapper);
        if (tenantDb!=null){
            return new Result<>(1,"用户名已经存在");
        }
        //2、将用户信息添加到数据库中
        String tenantPwd=tenant.getPwd();
        tenant.setPwd(SecureUtil.md5(tenantPwd));
        String snowflakeNextIdStr= IdUtil.getSnowflakeNextIdStr();
        tenant.setId(snowflakeNextIdStr);
        tenant.setAccessKey(snowflakeNextIdStr);
        tenant.setAccessSecurit("wo1shi2yi3ge4da5sha6bi7");
        tenant.setAuditStatus(0);
        tenantMapper.insert(tenant);
        return new Result<>(0,"success");
    }

    @Override
    public Result login(Tenant tenant) {
        if (tenant == null) {
            return new Result(1, "非法参数");
        }
        QueryWrapper<Tenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Tenant::getName, tenant.getName());
        Tenant tenantDb = this.baseMapper.selectOne(queryWrapper);
        if (tenantDb == null) {
            return new Result(1, "用户名或者密码不正确");
        }
        //比较密码
        String md5 = SecureUtil.md5(tenant.getPwd());
        if (md5.equals(tenantDb.getPwd())) {
            //颁发JWT令牌
            tenantDb.setPwd("");
            String token = JWTUtil.genTokenExpireByHour(tenantDb, 2);
            return new Result(0, "登入成功!!!", token);
        }

        return new Result(1, "用户名或者密码不正确");
    }

    @Override
    public Result sms(String phone) {
        //生成随机的四位数验证码
        int code = RandomUtil.randomInt(1000, 10000);
        //将验证码保存到redis数据库
        BoundValueOperations<String, String> codeOpt = redisTemplate.boundValueOps("login:" + phone);
        codeOpt.set(code+"");
        codeOpt.expire(10, TimeUnit.MINUTES);

        return SMSUtil.sendSMS(phone,code);
    }

    @Override
    public Result smsRegister(String phone) {
        //数据库查询是否有改手机号认证的用户
        QueryWrapper<Tenant> qw = new QueryWrapper();
        qw.lambda().eq(Tenant::getPhone,phone);
        Tenant tenant = this.baseMapper.selectOne(qw);
        if (tenant != null){
            return new Result(1,"手机号已注册！");
        }
        //生成随机的四位数验证码
        int code = RandomUtil.randomInt(1000, 10000);
        //将验证码保存到redis数据库
        BoundValueOperations<String, String> codeOpt = redisTemplate.boundValueOps("register:" + phone);
        codeOpt.set(code+"");
        codeOpt.expire(10, TimeUnit.MINUTES);
        return SMSUtil.sendSMS(phone,code);
    }

    @Override
    public Result smslogin(SMSDto smsDto) {
        if(SMSUtil.isPhone(smsDto.getPhone())){
            return new Result(1,"手机号错误！");
        }
        String codeDb = redisTemplate.boundValueOps("login:" + smsDto.getPhone()).get();
        if (StringUtils.isEmpty(codeDb)){
            return new Result(1,"验证码已过期！");
        }
        if (!smsDto.getCode().equals(codeDb)){
            return new Result(1,"验证码输入错误！");
        }
        //数据库查询是否有改手机号认证的用户
        QueryWrapper<Tenant> qw = new QueryWrapper();
        qw.lambda().eq(Tenant::getPhone,smsDto.getPhone());
        Tenant tenant = this.baseMapper.selectOne(qw);
        if (tenant == null){
            //未发现手机号绑定的tenant，自动注册新用户
            Tenant tenantNew = new Tenant();
            tenantNew.setName(smsDto.getPhone());
            tenantNew.setPwd(SecureUtil.md5(RandomUtil.randomString(6)));
            tenantNew.setPhone(smsDto.getPhone());
            tenantNew.setCompanyName("xx");
            tenantNew.setCompanyCode("123");
            String snowflakeNextIdStr= IdUtil.getSnowflakeNextIdStr();
            tenantNew.setId(snowflakeNextIdStr);
            tenantNew.setAccessKey(snowflakeNextIdStr);
            tenantNew.setAccessSecurit("wo1shi2yi3ge4da5sha6bi7");
            tenantNew.setAuditStatus(0);
            tenantMapper.insert(tenantNew);
            //颁发JWT令牌
            tenant.setPwd("");
            String token = JWTUtil.genTokenExpireByHour(tenant, 2);
            return new Result(0, "登入成功!!!", token);
        }else{
            //颁发JWT令牌
            tenant.setPwd("");
            String token = JWTUtil.genTokenExpireByHour(tenant, 2);
            return new Result(0, "登入成功!!!", token);
        }
    }

    @Override
    public Result register(Tenant tenant) {
        String codeDb = redisTemplate.boundValueOps("login:" + tenant.getPhone()).get();
        if (StringUtils.isEmpty(codeDb)){
            return new Result(1,"验证码已过期！");
        }
        if (!tenant.getCode().equals(codeDb)){
            return new Result(1,"验证码输入错误！");
        }
        tenant.setPwd(SecureUtil.md5(tenant.getPwd()));
        String snowflakeNextIdStr= IdUtil.getSnowflakeNextIdStr();
        tenant.setId(snowflakeNextIdStr);
        tenant.setAccessKey(snowflakeNextIdStr);
        tenant.setAccessSecurit("wo1shi2yi3ge4da5sha6bi7");
        tenant.setAuditStatus(0);
        if(baseMapper.insert(tenant) == 1){
            return new Result(0,"成功");
        }
        return new Result(1,"失败");
    }
}


